package com.hjs.servlet.regularinspection.regularinspection;

import com.hjs.bean.RegularInspection;
import com.hjs.bean.RegularInspectionView;
import com.hjs.mapper.RegularInspectionMapper;
import com.hjs.mapper.RoadAuditMapper;
import com.hjs.mapper.RoadMapper;
import com.hjs.mapper.ViewMapper;
import com.hjs.tools.Mapper;
import com.hjs.tools.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

@WebServlet("/RegularInspection/GetRegularInspectionPlan")
@Slf4j
public class GetRegularInspectionPlan extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*
         * 提供参数
         * departmentID（可不给）
         */
        RequestUtil requestUtil = new RequestUtil(request, response);
        try (SqlSession sqlSession = Mapper.getSqlSession(true)) {
            ViewMapper viewMapper = sqlSession.getMapper(ViewMapper.class);
            List<RegularInspectionView> allRegularInspectionView;
            //更新巡检计划
            updateRegularInspectionPlan(requestUtil, sqlSession);
            //根据是否传来departmentID决定查询所有还是部门
            if (requestUtil.getString("departmentID") == null) {
                allRegularInspectionView = viewMapper.getAllRegularInspectionView();
            } else {
                allRegularInspectionView = viewMapper.getRegularInspectionViewByDepartmentId(requestUtil.getInt("departmentID"));
            }
            //返回查询结果
            requestUtil.responseWrite(Mapper.toJsonString(allRegularInspectionView));
        } catch (Exception e) {
            log.error(e.toString());
            requestUtil.responseFail("查询失败,未知错误");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    private void updateRegularInspectionPlan(RequestUtil requestUtil, SqlSession sqlSession) {
        RoadAuditMapper mapper = sqlSession.getMapper(RoadAuditMapper.class);
        List<Integer> allRoadId;
        if (requestUtil.getString("departmentID") == null) {
            //没传departmentID就去获取所有正在养护的道路id
            allRoadId = mapper.getAllRoadId();
        } else {
            //传了departmentID就去获取这个部门管理的所有道路id
            allRoadId = mapper.getAllRoadIdByDepartmentId(requestUtil.getInt("departmentID"));
        }
        //遍历道路id
        allRoadId.forEach((roadId) -> {
            RoadMapper mapper2 = sqlSession.getMapper(RoadMapper.class);
            //根据道路id获取车行道id
            Integer roadwayId = mapper2.getRoadwayIdByRoadId(roadId);
            LocalDate lastDailyInspectionDate = getLastRegularInspectionDate(roadwayId, sqlSession);
            RegularInspection regularInspection = new RegularInspection();
            regularInspection.setRoadwayID(roadwayId);
            regularInspection.setGeneratedTime(LocalDateTime.now());
            RegularInspectionMapper regularInspectionMapper = sqlSession.getMapper(RegularInspectionMapper.class);
            if (lastDailyInspectionDate == null) {
                //获取到的最近巡检时间为空这表示没开始巡检 ,则直接插入一条巡检计划
                boolean sqlResult = regularInspectionMapper.addOneRegularInspection(regularInspection);
                Mapper.SessionEnd(sqlResult, sqlSession);
            } else {
                //如果现在与上一次时间差超过养护等级的天数,则新增一条巡检计划, 如果不超过三天就不会更新计划
                int interval = 365;
                if (ChronoUnit.DAYS.between(lastDailyInspectionDate, LocalDate.now()) >= interval) {
                    boolean sqlResult = regularInspectionMapper.addOneRegularInspection(regularInspection);
                    Mapper.SessionEnd(sqlResult, sqlSession);
                }
            }
        });
    }

    private LocalDate getLastRegularInspectionDate(int roadwayId, SqlSession sqlSession) {
        RegularInspectionMapper regularInspectionMapper = sqlSession.getMapper(RegularInspectionMapper.class);
        List<RegularInspection> regularInspectionByRoadId = regularInspectionMapper.getRegularInspectionByRoadId(roadwayId);
        if (regularInspectionByRoadId.size() == 0) {
            return null;
        }
        return regularInspectionByRoadId.get(regularInspectionByRoadId.size() - 1).getGeneratedTime().toLocalDate();
    }

}
